﻿using NAudio.Wave;
using NAudio.Wave.SampleProviders;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace AudioSourceManager
{
    public class AudioUdpStreamSource : IAudioSource
    {
        private UdpStreamReader udpStream;
        public BufferedWaveProvider waveProvider;

        public int DataReceivedBytes = 0;
        public int DataBufferBytes = 0;
        public int DataBufferLength = 0;


        protected override SampleChannel GetSampleChannel()
        {
            this.udpStream = new UdpStreamReader(AudioPath);
            udpStream.Start();
            if (udpStream.OnRecvMessage == null)
                udpStream.OnRecvMessage += DataReceived;
            WaveFormat wf = new WaveFormat(48000, 16, 2);
            waveProvider = new BufferedWaveProvider(wf);
            waveProvider.BufferDuration = TimeSpan.FromSeconds(10);
            waveProvider.DiscardOnBufferOverflow = true;
            SampleChannel sampleChannel = new SampleChannel(waveProvider, false);
            return sampleChannel;
        }

        /// <summary>
        /// 将收到的数据写入流中
        /// </summary>
        /// <param name="obj"></param>
        private void DataReceived(byte[] obj)
        {
            if (obj.Length > 0)
            {
                waveProvider.AddSamples(obj, 0, obj.Length);
                DataReceivedBytes = obj.Length;
                DataBufferBytes = waveProvider.BufferedBytes;
                DataBufferLength = waveProvider.BufferLength;
            }
        }

        public override void Dispose()
        {
            waveProvider = null;
            udpStream.OnRecvMessage -= DataReceived;
        }

        public override string GetLog()
        {
            return $"收到{DataReceivedBytes}bytes->缓冲：{DataBufferBytes  * 1.0f/ DataBufferLength}bytes";
        }

        public override bool TryMatch(string Path)
        {
            return URLReader.TryResolve(Path, out _);
        }
    }
}
